package com.mjh.zhujianju.service.base.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.livew.framework.base.dao.SysUserMapper;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.SysUserService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.enums.EStatus;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.agency.DeptUserMapper;
import com.mjh.zhujianju.dao.base.UserExtendMapper;
import com.mjh.zhujianju.enums.EducationEnum;
import com.mjh.zhujianju.enums.SexEnum;
import com.mjh.zhujianju.enums.YesNOEnum;
import com.mjh.zhujianju.excel.ColumnProperty;
import com.mjh.zhujianju.excel.ExcelUtil;
import com.mjh.zhujianju.excel.SheetInfo;
import com.mjh.zhujianju.model.agency.DepartmentEO;
import com.mjh.zhujianju.model.agency.DeptUserEO;
import com.mjh.zhujianju.model.base.UserExtendEO;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.service.base.UserExtendService;
import com.mjh.zhujianju.util.FileUrlAdapter;
import com.mjh.zhujianju.util.ShiroEncryption;
import com.mjh.zhujianju.vo.agency.DeptUserVO;
import com.mjh.zhujianju.vo.base.SysUserVO;

/**
 * @author liuyang
 * @Description: 用户党员信息
 * @date 2018/8/8 22:50
 */
@Service
public class UserExtendServiceImpl extends BaseServiceImpl<UserExtendEO> implements UserExtendService {

	@Autowired
	private UserExtendMapper userExtendMapper;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private DeptUserMapper deptUserMapper;

	@Autowired
	private SysUserService userService;

	@Autowired
	private FileService fileService;

	@Resource
	private DeptUserService deptUserService;

	@Resource
	private HttpSession session;

	public UserExtendServiceImpl(UserExtendMapper userExtendMapper) {
		super(userExtendMapper);
	}

	@Override
	public List<UserExtendEO> queryUserExtendByUserIds(List<Long> userIds) {
		return userExtendMapper.queryUserExtendByUserIds(userIds);
	}

	@Override
	public UserExtendEO queryUserExtendByUserId(Long userId) {
		return userExtendMapper.selectByPrimaryUserId(userId);
	}

	@Override
	public PagedResult<SysUserVO> getVOList(SysUserVO vo) {
		Integer pageNo = vo.getPageNo() == null ? 1 : vo.getPageNo();
		Integer pageSize = vo.getPageSize() == null ? 15 : vo.getPageSize();
		PageHelper.startPage(pageNo, pageSize);
		SysUser user = new SysUser();
		BeanUtils.copyProperties(vo, user);
		List<SysUser> list = sysUserMapper.selectWorkUser(user);
		PagedResult<SysUser> page = PagedBeanUtil.toPagedResult(list);
		PagedResult<SysUserVO> result = new PagedResult<>();
		BeanUtils.copyProperties(page, result);
		if (!XTListUtils.isEmpty(list)) {
			List<Long> ids = XTEntityUtils.getIdList(list);
			List<SysUserVO> voList = new ArrayList<SysUserVO>();
			Map<Long, FileEO> files = fileService.getMapTopOne(ids, SysUser.class.getName(), null);
			Map<Long, UserExtendEO> map = getUserExtendByUserIds(ids);
			Map<Long, DeptUserVO> deptUserMap = deptUserService.getDeptByUserIds(ids);
			for (SysUser u : list) {
				SysUserVO d = new SysUserVO();
				BeanUtils.copyProperties(u, d);
				if (map != null) {
					UserExtendEO ext = map.get(u.getId());
					if (ext != null) {
						ext.setSex(SexEnum.getName(ext.getSex()));
						ext.setIsParty(YesNOEnum.getName(ext.getIsParty()));
					}
					d.setUserExtendEO(ext);
				}
				if (deptUserMap != null) {
					DeptUserVO du = deptUserMap.get(u.getId());
					d.setDeptUser(du);
				}
				voList.add(d);
				FileEO file = files.get(d.getId());
				if (file != null) {
					d.setFileId(file.getId());
				}
			}
			result.setDataList(voList);
		}
		return result;
	}

	@Override
	public PagedResult<SysUserVO> getUserList(SysUserVO vo) {
		// 根据部门id查询部门下所有用户id
		// 查询部门-人员 关系 List
		List<DeptUserEO> deptUserEOList = deptUserMapper.selectListByCondition(vo.getDeptUser());
		if (CollectionUtils.isEmpty(deptUserEOList)) {
			return null;
		}

		// 获取所有userId
		List<Long> userIds = deptUserEOList.stream().map(deptUserEO1 -> deptUserEO1.getUserId()).distinct()
				.collect(Collectors.toList());

		Integer pageNo = vo.getPageNo() == null ? 1 : vo.getPageNo();
		Integer pageSize = vo.getPageSize() == null ? 15 : vo.getPageSize();
		PageHelper.startPage(pageNo, pageSize);
		List<SysUser> list = sysUserMapper.selectByIdList(userIds);
		PagedResult<SysUser> page = PagedBeanUtil.toPagedResult(list);
		PagedResult<SysUserVO> result = new PagedResult<>();
		BeanUtils.copyProperties(page, result);
		if (!XTListUtils.isEmpty(list)) {
			List<Long> ids = XTEntityUtils.getIdList(list);
			List<SysUserVO> voList = new ArrayList<SysUserVO>();
			Map<Long, FileEO> files = fileService.getMapTopOne(ids, SysUser.class.getName(), null);
			Map<Long, UserExtendEO> map = getUserExtendByUserIds(ids);
			Map<Long, DeptUserVO> deptUserMap = deptUserService.getDeptByUserIds(ids);
			for (SysUser u : list) {
				SysUserVO d = new SysUserVO();
				BeanUtils.copyProperties(u, d);
				if (map != null) {
					UserExtendEO ext = map.get(u.getId());
					if (ext != null) {
						ext.setSex(SexEnum.getName(ext.getSex()));
						ext.setIsParty(YesNOEnum.getName(ext.getIsParty()));
					}
					d.setUserExtendEO(ext);
				}
				if (deptUserMap != null) {
					DeptUserVO du = deptUserMap.get(u.getId());
					d.setDeptUser(du);
				}
				voList.add(d);
				FileEO file = files.get(d.getId());
				if (file != null) {
					d.setFileId(file.getId());
				}
			}
			result.setDataList(voList);
		}
		return result;
	}

	@Override
	public Map<Long, UserExtendEO> getUserExtendByUserIds(List<Long> userIds) {
		List<UserExtendEO> list = userExtendMapper.queryUserExtendByUserIds(userIds);
		if (XTListUtils.isEmpty(list)) {
			return null;
		}
		Map<Long, UserExtendEO> map = new HashMap<>();
		for (UserExtendEO userExtendEO : list) {
			map.put(userExtendEO.getUserId(), userExtendEO);
		}
		return map;
	}

	@Override
	@Transactional
	public void saveInfo(SysUserVO vo) throws XTBusinessException {
		if (vo.getUsername() == null || vo.getNickname() == null) {
			throw new XTBusinessException("参数错误");
		}
		SysUser user = new SysUser();
		BeanUtils.copyProperties(vo, user);
		user.setPassword(ShiroEncryption.encrptText(user.getPassword()));
		user.setStatus(EStatus.active.getCode());
		userService.save(user);
		UserExtendEO ext = new UserExtendEO();
		BeanUtils.copyProperties(vo.getUserExtendEO(), ext);
		ext.setUserId(user.getId());
		ext.setStatus(EStatus.active.getCode());
		this.save(ext);
		DeptUserEO du = new DeptUserEO();
		BeanUtils.copyProperties(vo.getDeptUser(), du);
		du.setStatus(EStatus.active.getCode());
		du.setUserId(user.getId());
		deptUserService.save(du);
		if (vo.getFileId() != null) {
			List<Long> files = new ArrayList<>();
			files.add(vo.getFileId());
			this.fileService.updateList(files, user.getId(), SysUser.class.getName());
		}
	}

	@Override
	@Transactional
	public void updateInfo(SysUserVO vo) throws XTBusinessException {
		if (vo.getNickname() == null || vo.getId() == null) {
			throw new XTBusinessException("参数错误");
		}
		SysUser user = new SysUser();
		BeanUtils.copyProperties(vo, user);
		user.setStatus(EStatus.active.getCode());
		userService.updateByPrimaryKey(user);
		UserExtendEO ext2 = this.userExtendMapper.selectByPrimaryUserId(vo.getId());
		UserExtendEO ext = new UserExtendEO();
		BeanUtils.copyProperties(vo.getUserExtendEO(), ext);
		ext.setUserId(user.getId());
		ext.setStatus(EStatus.active.getCode());
		ext.setId(ext2.getId());
		this.updateByPrimaryKeySelective(ext);
		DeptUserEO du = new DeptUserEO();
		DeptUserVO du2 = deptUserService.getDeptByUserId(vo.getId());
		BeanUtils.copyProperties(vo.getDeptUser(), du);
		du.setStatus(EStatus.active.getCode());
		du.setUserId(user.getId());
		du.setId(du2.getId());
		deptUserService.updateByPrimaryKeySelective(du);
		List<Long> files = new ArrayList<>();
		files.add(vo.getFileId());
		this.fileService.updateList(files, user.getId(), SysUser.class.getName());
	}

	@Override
	public SysUserVO getInfo(Long id) throws XTBusinessException {
		SysUserVO vo = new SysUserVO();
		SysUser user = sysUserMapper.selectByPrimaryKey(id);
		BeanUtils.copyProperties(user, vo);
		vo.setPassword(null);
		UserExtendEO ext = this.userExtendMapper.selectByPrimaryUserId(id);
		if (ext != null) {
			ext.setSexName(SexEnum.getName(ext.getSex()));
			ext.setPartyName(YesNOEnum.getName(ext.getIsParty()));
			ext.setEducationName(EducationEnum.getName(ext.getEducation()));
		}
		vo.setUserExtendEO(ext);
		// 部门
		DeptUserVO du = deptUserService.getDeptByUserId(id);
		if (du != null) {
			List<FileEO> files = fileService.getFileById(du.getDeptId(), DepartmentEO.class.getName(), null);
			if (!XTListUtils.isEmpty(files)) {// 部门图片
				du.setRemark2(FileUrlAdapter.assemblyAction(files.get(0).getId()));
			}
		}
		vo.setDeptUser(du);
		// 头像
		List<FileEO> files = fileService.getFileById(id, SysUser.class.getName(), null);
		if (!XTListUtils.isEmpty(files)) {
			vo.setFiles(files);
			vo.setFileId(files.get(0).getId());
			vo.setHeadImage(FileUrlAdapter.assemblyAction(files.get(0).getId()));
		}
		return vo;
	}

	@Override
	@Transactional
	public int delByPrimaryKey(UserExtendEO t) throws XTBusinessException {
		SysUser user = new SysUser();
		user.setId(t.getId());
		userService.delByPrimaryKey(user);
		deptUserService.delDeptByUserId(t.getId());
		return delByUserId(t.getId());
	}

	@Override
	public int delByUserId(Long userId) throws XTBusinessException {
		UserExtendEO ext = new UserExtendEO();
		ext.setUpdateTime(new Date());
		ext.setUpdateUserId(XTCurrentUser.getCurrentUserId(session));
		ext.setUserId(userId);
		return this.userExtendMapper.delByUserId(ext);
	}

	@Override
	@Transactional
	public void updateWorkInfo(SysUserVO vo) throws XTBusinessException {
		UserExtendEO ext = new UserExtendEO();
		BeanUtils.copyProperties(vo, ext);
		UserExtendEO extEO = userExtendMapper.selectByPrimaryUserId(vo.getId());
		ext.setUpdateTime(new Date());
		ext.setUpdateUserId(XTCurrentUser.getCurrentUserId(session));
		ext.setUserId(vo.getId());
		ext.setId(extEO.getId());
		this.userExtendMapper.updateByPrimaryKeySelective(ext);
		SysUser user = new SysUser();
		user.setPhone(vo.getPhone());
		user.setNickname(vo.getNickname());
		user.setId(vo.getId());
		userService.updateByPrimaryKeySelective(user);
		if (vo.getFileId() != null) {
			List<Long> files = new ArrayList<>();
			files.add(vo.getFileId());
			this.fileService.updateList(files, user.getId(), SysUser.class.getName());
		}
	}

	@Override
	public void importUserList(MultipartFile file) throws XTBusinessException, Exception {
		SheetInfo sheetInfo = new SheetInfo(SheetInfo.DEFAILT_TITLE_INFO);
		List<ColumnProperty> columnProperties = new LinkedList<>();
		columnProperties.add(new ColumnProperty.Builder().columnName("姓名").fieldName("nickname").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("手机号").fieldName("phone").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("帐号").fieldName("username").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("密码").fieldName("password").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("性别").fieldName("sex").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("职位").fieldName("position").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("部门").fieldName("deptName").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("是否是党员").fieldName("party").build());
		columnProperties.add(new ColumnProperty.Builder().columnName("入党日期").fieldName("partyTime").build());
		sheetInfo.setColumnProperties(columnProperties);
		Map map = new HashMap();
		map = ExcelUtil.getExcel(file, sheetInfo);
		Object obj = map.get(SheetInfo.DEFAILT_TITLE_INFO);
		List<Map<String,String>> list= (List)obj;
		if(!XTListUtils.isEmpty(list)) {
			for (Map<String, String> map2 : list) {
				SysUser user = new SysUser();
				user.setNickname(map2.get("nickname"));
				user.setPhone("phone");
				user.setPassword("");
			}
		}
		System.out.println(list);
	}

	public static <T> T  JSONToObj(String jsonStr, Class<T> obj) {
		T t = null;
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			t = objectMapper.readValue(jsonStr, obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

}
